use std::time::{Duration, Instant};

/// 任务执行时间信息
#[derive(Debug, Clone)]
pub struct TaskTiming {
    pub started_at: Option<Instant>,
    pub finished_at: Option<Instant>,
    pub duration: Option<Duration>,
}

impl Default for TaskTiming {
    fn default() -> Self {
        Self {
            started_at: None,
            finished_at: None,
            duration: None,
        }
    }
}

impl TaskTiming {
    /// 标记任务开始
    pub fn start(&mut self) {
        self.started_at = Some(Instant::now());
        self.finished_at = None;
        self.duration = None;
    }

    /// 标记任务完成
    pub fn finish(&mut self) {
        self.finished_at = Some(Instant::now());
        if let Some(started) = self.started_at {
            self.duration = Some(started.elapsed());
        }
    }

    /// 获取运行时间（如果任务正在运行）
    pub fn running_duration(&self) -> Option<Duration> {
        self.started_at.map(|start| start.elapsed())
    }

    /// 获取格式化的持续时间字符串
    pub fn format_duration(&self) -> String {
        let duration = self.duration.or_else(|| self.running_duration());

        match duration {
            Some(d) => {
                let secs = d.as_secs();
                if secs < 60 {
                    format!("{}秒", secs)
                } else if secs < 3600 {
                    format!("{}分{}秒", secs / 60, secs % 60)
                } else {
                    format!("{}小时{}分", secs / 3600, (secs % 3600) / 60)
                }
            }
            None => "未开始".to_string(),
        }
    }
}

/// 任务工具函数
pub mod utils {
    /// 验证任务名称是否有效
    pub fn is_valid_task_name(name: &str) -> bool {
        !name.trim().is_empty() && name.len() <= 100
    }

    /// 清理任务名称
    pub fn sanitize_task_name(name: &str) -> String {
        name.trim().chars().take(100).collect()
    }

    /// 格式化任务状态显示
    pub fn format_task_status(status: &crate::app::TaskStatus) -> &'static str {
        match status {
            crate::app::TaskStatus::Pending => "等待中",
            crate::app::TaskStatus::Running => "运行中",
            crate::app::TaskStatus::Finished => "已完成",
            crate::app::TaskStatus::Failed => "失败",
            crate::app::TaskStatus::Stopped => "已停止",
        }
    }
}
